package com.base.cn.platform.os.common.mybatis.sharding;

import com.alibaba.druid.sql.ast.SQLExpr;
import com.alibaba.druid.sql.ast.expr.SQLBinaryOpExpr;
import com.alibaba.druid.sql.ast.expr.SQLBinaryOperator;
import com.alibaba.druid.sql.ast.expr.SQLIdentifierExpr;
import com.alibaba.druid.sql.ast.expr.SQLPropertyExpr;

import java.util.Map;
import java.util.Set;

/**
 * 分片工具类
 *
 * @author s.li
 * @create 2019-05-23 14:03
 */
public class ShardingValueUtil {

    public static void addShardingValue(Set<String> columnSet,
                                        Map<String,Object> shardingValues,
                                        SQLBinaryOpExpr sqlBinaryOpExpr){
        if(columnSet !=null && shardingValues !=null){
            SQLExpr leftSqlExpr = sqlBinaryOpExpr.getLeft();
            if(leftSqlExpr instanceof SQLPropertyExpr || leftSqlExpr instanceof SQLIdentifierExpr){
                addValue(columnSet,shardingValues,sqlBinaryOpExpr);
            }
            SQLExpr rightSqlExpr = sqlBinaryOpExpr.getRight();
            if(rightSqlExpr instanceof SQLPropertyExpr || leftSqlExpr instanceof SQLIdentifierExpr){
                addValue(columnSet,shardingValues,sqlBinaryOpExpr);
            }
            if(rightSqlExpr instanceof SQLBinaryOpExpr){
                addShardingValue(columnSet,shardingValues,(SQLBinaryOpExpr)rightSqlExpr);
            }
        }
    }

    private static void addValue(Set<String> columnSet,
                                 Map<String,Object> shardingValues,
                                 SQLBinaryOpExpr sqlBinaryOpExpr){
        SQLExpr leftExpr = sqlBinaryOpExpr.getLeft();
        SQLBinaryOperator binaryOperator = sqlBinaryOpExpr.getOperator();
        if(leftExpr instanceof SQLIdentifierExpr){
            SQLIdentifierExpr leftIdentifierExpr = (SQLIdentifierExpr) leftExpr;
            String name = leftIdentifierExpr.getName().replaceAll("`","");
            SQLExpr rightSqlExpr = sqlBinaryOpExpr.getRight();
            if(rightSqlExpr!=null && !(rightSqlExpr instanceof SQLPropertyExpr)
                    && columnSet.contains(name.toLowerCase()) && binaryOperator.getName().equals("=")){
                shardingValues.put(name,rightSqlExpr.toString());
            }
        }
        if(leftExpr instanceof  SQLPropertyExpr){
            SQLPropertyExpr leftPropertyExpr = (SQLPropertyExpr)sqlBinaryOpExpr.getLeft();
            SQLExpr rightSqlExpr = sqlBinaryOpExpr.getRight();
            String name = leftPropertyExpr.getName().replaceAll("`","");
            if(rightSqlExpr!=null && !(rightSqlExpr instanceof SQLPropertyExpr)
                    && columnSet.contains(name.toLowerCase()) && binaryOperator.getName().equals("=")){
                shardingValues.put(name,rightSqlExpr.toString());
            }
        }
    }
}
